package org.example.chapter3_3.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.chapter3_3.entity.User;
import org.example.chapter3_3.service.LoginService;
import org.example.chapter3_3.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Controller
public class UserContorller {
    //访问项目主页
    @RequestMapping(value ={"/index","/main"} )//项目根目录
    public String index(){
        log.info("打开主页");
        return  "index";
    }

    //访问登录页面
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ModelAndView login(ModelAndView mv){
        log.info("打开登录页面");
        mv.setViewName("login");
        return mv;
    }
    @Autowired
    LoginService loginService;

    //登录验证
    @RequestMapping(value = "login",params = {"name","password"},name="登录验证",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView userlogin(ModelAndView mv,User user) {
        log.info(":"+user);
        if (loginService.login(user.getName(), user.getPassword())) {
            mv.setViewName("index");
            mv.addObject("users",user);
        } else {
            mv.setViewName("login");
            mv.addObject("error","登录失败");
        }
        return mv;
    }
    //接收访问注册界面的请求，并返回注册页面
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public ModelAndView showregister(ModelAndView modelAndView){
        //创建mv对象
        //ModelAndView modelAndView = new ModelAndView();
        //指定返回的视图
        modelAndView.setViewName("register");
        //添加实体类对象数据
        modelAndView.addObject("user",new User());
        return modelAndView;
    }
    @Autowired
    UserService userService;
    //服务器接收注册请求
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ModelAndView handleregister(ModelAndView mv,User user){
        //处理注册请求
        try {
            userService.registerUser(user);
            mv.addObject("success","注册成功");
        }catch (Exception e){
            log.error(e.getMessage());
            mv.addObject("error","注册失败");
        }
        return mv;
    }

}
